-- UICareerLine
-- Create by huanghr
-- 称号线路图

require "game/ui/form/hero/UISkillInfo"

UICareerLine = class("UICareerLine", function()
    return cc.Layer:create();
end)

function UICareerLine.create(curPage)
    return UICareerLine.new(curPage);
end

-- 技能系别标签页数
local PAGE_PART_NUM = 4;

-- 冒险系别的ID值
local DEPARTMENT_RISKER = 4;
local DEPARTMENT_DRAGON = 8;

-- 职业最大的阶位
local MAX_RANK = 5;

-- 构造函数
function UICareerLine:ctor(curPage)
    -- 初始化
    self:setName("UICareerLine");
    local node = cc.CSLoader:createNode("layout/hero/CareerLine.csb");
    self:addChild(node);
    self.node = node;

    self:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 1);

    local pagePart = findChildByName(self.node, "CT/page_part");
    self.pagePart = pagePart;

    -- 记录数据
    self.pet = ME.user:getActivePet();
    self.curPage = curPage;

    -- 注册点击事件
    self:registerTouchEvent();

    -- 注册回调事件
    self:registerEventCallback();

    -- 重绘
    self:redraw();

    -- 适配
    self:resize();
end

-- 注册点击事件
function UICareerLine:registerTouchEvent()
    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_return");
            -- 关闭当前界面
            UIMgr.getCurrentScene():removeFormByName("UICareerLine");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    -- 注册分页按钮点击事件
    local pagePart = findChildByName(self.node, "CT/page_part");
    for i = 1, PAGE_PART_NUM do
        local btn = findChildByName(pagePart, "btn_page" .. i);

        local function onBtnClick(sender, eventType)
            if eventType == ccui.TouchEventType.ended then
                AudioM.playFx("button_select");

                -- 设置选中效果
                self.curPage = i;
                self:redraw();
            end
        end
        btn:addTouchEventListener(onBtnClick);
    end

    -- 初始化标签位置,上移150
    local vOffset = 150;
    local pagePart = findChildByName(self.node, "CT/page_part");
    self.btns = {};
    self.lights = {};
    for i = 1, PAGE_PART_NUM do
        local btn = findChildByName(pagePart, "btn_page" .. i);
        btn:setPositionY(btn:getPositionY() + vOffset);
        table.insert(self.btns, btn);
        local light = findChildByName(pagePart, "light" .. i);
        light:setPositionY(light:getPositionY() + vOffset);
        table.insert(self.lights, light);
    end
end

-- 注册事件处理回调函数
function UICareerLine:registerEventCallback()
    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(ev)
        if ev == "exit" then
            cclog("UICareerLine 界面析构清理");
            EventMgr.removeAll("UICareerLine");
        elseif ev == "enter" then
            -- 标签落下的效果
            self:playTabEffect();
        end
    end);
end

-- 重绘
function UICareerLine:redraw()
    local scrollPanel = findChildByName(self.node, "CT/scrollview");
    scrollPanel:removeAllChildren();

    -- 重绘技能
    self:redrawSkill();

    -- 图标宽、高
    local iconWidth  = 850;
    local iconHeight = 720;

    -- 设置滚动区域的尺寸
    if iconWidth > scrollPanel:getInnerContainerSize().width then
        scrollPanel:setInnerContainerSize(cc.size(iconWidth, scrollPanel:getInnerContainerSize().height));
    end

    -- 获取已激活的系别
    local deptList = CareerM.getDepartmentList(self.pet);
    local curDeptId = deptList[self.curPage];

    local itemNode = nil;

    -- 根据系别ID选择合适的线路图
    if curDeptId == DEPARTMENT_RISKER then
        itemNode = cc.CSLoader:createNode("layout/hero/Risker.csb");
    elseif curDeptId == DEPARTMENT_DRAGON then
        itemNode = cc.CSLoader:createNode("layout/hero/DragonLineNode.csb");
    else
        itemNode = cc.CSLoader:createNode("layout/hero/SoldierLine.csb");
    end

    -- 称号系别
    local titleLabel = findChildByName(itemNode, "title1");
    TextStyleM.setTextStyle(titleLabel, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_ORANGE, true, -4, nil, nil, nil, nil, true);
    titleLabel:setString(CareerM.getDepartmentName(curDeptId));

    local titleLabel2= findChildByName(itemNode, "title2");
    TextStyleM.setTextStyle(titleLabel2, TextStyleM.TEXT_SIZE_MINI, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true, -4, nil, nil, nil, nil, true);
    titleLabel2:setString(getLocStr("career_name"));

    local careerNode = cc.CSLoader:createNode("layout/hero/CareerNode.csb");
    local widget = replaceNodeWithWidget(careerNode);

    -- 获得某一系别的称号id
    local ids = CareerM.getIdsByDepartment(curDeptId);
    table.sort(ids);

    -- 获取已学习的称号和等级
    local pet = self.pet;
    local careerData = pet:getCareerData(curDeptId);

    local hasLearnIds = {};
    local hasLearnLevel = {};
    for k = 1, #careerData do
        local info = careerData[k];
        local id = info["career"];
        table.insert(hasLearnIds, info["career"]);
        hasLearnLevel[id] = info["level"];
    end

    -- 获取可学习的路线的称号
    local ret = self:learnLine(curDeptId);

    local canLearnIds = {};
    for _, ids1 in pairs(ret) do
        for i = 1, #ids1 do
            table.insert(canLearnIds, ids1[i]);
        end
    end

    local noLockIds = self:removeRepeatIds(canLearnIds);

    -- 获取当前地牢开放的职业最高阶位
    local maxRank = CareerM.getDungeonMaxCareerRank(curDeptId);

    -- 已学习的等级
    local lightStarPath = "images/ui/symbol/star_little.png";
    local darkStarPath  = "images/ui/symbol/star_little2.png";

    -- 遍历所有称号
    for i = 1, #ids, 1 do
        local careerNode = itemNode:getChildByName("career_" .. i);
        local child = widget:clone();
        child:setName("career" .. i);

        local careerInfo = CareerM.getCareerInfo(ids[i]);
        local iconImg   = findChildByName(child, "icon");
        local nameLabel = findChildByName(child, "name");

        if table.indexOf(noLockIds, ids[i]) ~= -1 then
            if careerInfo["rank"] > maxRank then
                -- 大于当前开放的等级
                iconImg:loadTexture(getCareerIconPath("rank"..careerInfo["rank"]));
                TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_MINI, TextStyleM.TEXT_COLOR_LIGHT_BLUE, true, -4, nil, nil, nil, nil, true);
                nameLabel:setString(careerInfo["name"]);
                nameLabel:setVisible(false);

                local icon = findChildByName(child, "icon")
                local function onClick(sender, eventType)
                    if eventType == ccui.TouchEventType.began then
                        icon:runAction(cc.ScaleTo:create(0.1, 0.65));
                    elseif eventType == ccui.TouchEventType.canceled then
                        icon:runAction(cc.ScaleTo:create(0.1, 0.7));
                    elseif eventType == ccui.TouchEventType.ended then
                        icon:runAction(cc.ScaleTo:create(0.1, 0.7));
                        AudioM.playFx("button_click");
                        alert(getLocStr("cant_see_career_info"));
                    end
                end
                icon:addTouchEventListener(onClick);
            else
                -- 能加入该职业，则正常显示
                local result = FormulaM.invoke("CAN_JOIN_CAREER", self.pet, ids[i]);
                if true == result then
                    iconImg:loadTexture(getCareerIconPath(careerInfo["icon"]));
                    TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_MINI, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true, -4, nil, nil, nil, nil, true);
                    nameLabel:setString(careerInfo["name"]);
                else
                    iconImg:loadTexture(getCareerIconPath("rank"..careerInfo["rank"]));
                    TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_MINI, TextStyleM.TEXT_COLOR_LIGHT_BLUE, true, -4, nil, nil, nil, nil, true);
                    nameLabel:setString(careerInfo["name"]);
                    nameLabel:setVisible(false);
                end

                self:iconTouchEvent(child, ids[i]);
            end

            --
            careerNode:addChild(child);
        elseif table.indexOf(hasLearnIds, ids[i]) ~= -1 then
            -- 已学习显示当前等级
            local starNode = findChildByName(child, "star_node");
            local maxStar = careerInfo["max_level"];
            local rank = careerInfo["rank"];

            local starLayer;
            local starScale = 1;
            local offsetY = 0;

            -- 最大等级需要特殊显示
            if rank == MAX_RANK then
                -- 获取已满级的特性数量
                local curStar = CareerM.getLevelUpperFeatureNum(self.pet, ids[i]);
                lightStarPath = "images/ui/symbol/moon_01.png";
                darkStarPath  = "images/ui/symbol/moon_02.png";
                if curStar > 3 then
                    curStar = 3;
                end
                starLayer = createStarLayerEx(curStar, 3, lightStarPath, darkStarPath, "center", -0.7);
                starScale = 0.65;
                offsetY = 6;
            else
                lightStarPath = "images/ui/symbol/star_little.png";
                darkStarPath  = "images/ui/symbol/star_little2.png";
                maxStar = math.min(maxStar, MAX_RANK);
                local curStar = hasLearnLevel[ids[i]];
                starLayer = createStarLayerEx(curStar, maxStar, lightStarPath, darkStarPath, "center", -0.7);
            end

            starNode:removeAllChildren();
            starNode:addChild(starLayer);
            starNode:setScale(starScale);
            local x = starNode:getPositionX();
            local y = starNode:getPositionY() - offsetY;
            starNode:setPosition(cc.p(x, y));

            iconImg:loadTexture(getCareerIconPath(careerInfo["icon"]));
            TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_MINI, TextStyleM.TEXT_COLOR_LIGHT_BLUE, true, -4, nil, nil, nil, nil, true);
            nameLabel:setString(careerInfo["name"]);

            careerNode:addChild(child);

            self:iconTouchEvent(child, ids[i]);
        else
            -- 加载上锁的
            iconImg:loadTexture(getCareerIconPath("rank"..careerInfo["rank"]));
            TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_MINI, TextStyleM.TEXT_COLOR_LIGHT_BLUE, true, -4, nil, nil, nil, nil, true);
            nameLabel:setString(careerInfo["name"]);
            nameLabel:setVisible(false);

            careerNode:addChild(child);

            local icon = findChildByName(child, "icon")
            local function onClick(sender, eventType)
                if eventType == ccui.TouchEventType.began then
                    icon:runAction(cc.ScaleTo:create(0.1, 0.65));
                elseif eventType == ccui.TouchEventType.canceled then
                    icon:runAction(cc.ScaleTo:create(0.1, 0.7));
                elseif eventType == ccui.TouchEventType.ended then
                    icon:runAction(cc.ScaleTo:create(0.1, 0.7));
                    AudioM.playFx("button_click");
                    alert(getLocStr("cant_see_career_info"));
                end
            end
            icon:addTouchEventListener(onClick);
        end
    end

    itemNode:setPosition(405, 360);
    scrollPanel:addChild(itemNode);
end

-- 获得可学习线路
function UICareerLine:learnLine(CurDeptId)
    -- 冈布奥学习过的称号
    local pet = self.pet;
    local careerData = pet:getCareerData(CurDeptId);
    local careerSize = #careerData;
    local firstId = 1;

    local ret = {};
    if careerSize == 0 then
        -- 默认取初始职业
        local initCareer = CareerM.getDepartmentInfo(CurDeptId, "init_career");
        table.insert(ret, {initCareer});
        firstId = initCareer;
    else
        -- 获取已学习的最后一个职业
        local info = careerData[careerSize];
        firstId = info["career"];
    end

    -- 获取下级可学习的职业
    local nextCareers = CareerM.getCareerInfo(firstId, "next");
    table.insert(ret, nextCareers);

    -- 通过递归获取职业的可学的职业
    local function getCanChooseCareer(nextCareers)
        -- 递归结束条件
        if nextCareers == nil or #nextCareers == 0 then
            return;
        end

        for i = 1, #nextCareers do
            local nextCareers = CareerM.getCareerInfo(nextCareers[i], "next");
            if nextCareers ~= nil and #nextCareers ~= 0 then
                 table.insert(ret, nextCareers);
                getCanChooseCareer(nextCareers);
             end
        end
    end

    -- 获取可选称号
    getCanChooseCareer(nextCareers);
    return ret;
end

-- 去掉当前table重复的ID值
function UICareerLine:removeRepeatIds(ids)
     local ret = {};

     if #ids == 0 then
        return {};
     end

     table.insert(ret,ids[1]);

     -- 去重复
     for i = 1 ,#ids do
         local repeatFlag = false;
         for j = 1, #ret do
            if ret[j] == ids[i] then
               repeatFlag = true;
            end
         end

         if repeatFlag ~= true then
            table.insert(ret, ids[i]);
         end
     end

     return ret;
end

-- 显示称号系别标签页
function UICareerLine:redrawSkill()
    -- 获取已激活的系别
    local deptList  = CareerM.getDepartmentList(self.pet);
    local deptOrder = self.pet:query("department_order");
    local activeNum = #deptList;

    -- 选中和未选中的颜色设置
    local normalColor = TextStyleM.TEXT_COLOR_NORMAL;
    local blendColor = TextStyleM.TEXT_COLOR_BLEND;

    -- 显示技能分页按钮
    local pagePart = self.pagePart;
    local kerning = 0;
    if not isFullWidthLang() then
        kerning = -3;
    end

    -- 显示技能分页按钮
    local pagePart = self.pagePart;
    for i = 1, PAGE_PART_NUM do
        local btn = findChildByName(pagePart, "btn_page" .. i);

        -- 仅显示已激活的系别
        if i <= activeNum then
            btn:setVisible(true);
            local style = deptList[i];
            local name = CareerM.getDepartmentInfo(style, "name");
            local nameLabel = findChildByName(btn, "name");
            local numLabel  = findChildByName(btn, "num");

            if i == 1 then
                btn:setTitleText("");
                TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true, kerning);
                nameLabel:setString(name);
            else
                -- 其他类型的系别，需要特殊显示
                TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true, kerning);
                TextStyleM.setTextStyle(numLabel, TextStyleM.TEXT_SIZE_TINY, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true, kerning);
                btn:setTitleText("");
                nameLabel:setString(name);
                numLabel:setString("×2");
            end
        else
            btn:setVisible(false);
        end

        TextStyleM.setTextStyle(btn, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true, kerning);

        local light = findChildByName(pagePart, "light" .. i);

        -- 设置分页按钮选中效果
        if i == self.curPage then
            btn:setTouchEnabled(false);
            btn:setBright(false);
            btn:setColor(normalColor);
            light:setVisible(true);
        else
            btn:setTouchEnabled(true);
            btn:setBright(true);
            btn:setColor(blendColor);
            light:setVisible(false);
        end
    end
end

-- 标签落下的效果
function UICareerLine:playTabEffect()
    local vOffset = 150;

    local function play()
        -- 掉落并小幅回弹
        local function dropDown(node, index)
            local pos = cc.p(node:getPosition());
            local delay = cc.DelayTime:create(0.2 * (index - 1));
            local moveDown = cc.MoveTo:create(0.2, cc.p(pos.x, pos.y - vOffset - 5));
            local moveBack = cc.MoveTo:create(0.2, cc.p(pos.x, pos.y - vOffset));
            local action = cc.Sequence:create(delay, moveDown, moveBack);
            node:runAction(action);
        end

        for i = 1, PAGE_PART_NUM do
            local btn = self.btns[i];
            local light = self.lights[i];

            dropDown(btn, i);
            dropDown(light, i);
        end
    end

    -- tab的动画效果
    performWithDelay(self, play, 0.1);
end

-- 注册点击
function UICareerLine:iconTouchEvent(child, careerId)
    local icon = findChildByName(child, "icon")
    local function onClick(sender, eventType)
        if eventType == ccui.TouchEventType.began then
            icon:runAction(cc.ScaleTo:create(0.1, 0.65));
        elseif eventType == ccui.TouchEventType.canceled then
            icon:runAction(cc.ScaleTo:create(0.1, 0.7));
        elseif eventType == ccui.TouchEventType.ended then
            icon:runAction(cc.ScaleTo:create(0.1, 0.7));
            AudioM.playFx("button_click");
            -- 关闭当前界面
            UIMgr.getCurrentScene():removeFormByName("UISkillInfo");

            local uiForm = UISkillInfo.create(careerId);
            UIMgr.getCurrentScene():addForm(uiForm);
        end
    end
    icon:addTouchEventListener(onClick);
end

-- 上锁按钮

-- 适配
function UICareerLine:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end